<?php

namespace App\Http\Controllers\Api\Order;

use DB;

use Carbon\Carbon;

use App\Models\Tg\Tg; //团购维护表

use App\Models\Bill\Bill;  //订单主表

use Illuminate\Http\Request;

use App\Models\Mall\MallZiti; //门店自提网点表

use App\Models\Bill\BillTrace; //订单轨迹表

use App\Models\Bill\BillGoods; //订单商品表

use App\Models\Mall\MallMaster; //购物中心表

use App\Models\Bill\BillCodePool; //订单生码表

use App\Models\ConfigureFunction; //设置表

use App\Http\Controllers\Controller;

use App\Models\Customer\Customer; //会员表

use App\Models\Goods\GoodsSaleEdit; //待发布商品表

use Illuminate\Support\Facades\Redis as Redis;

use App\Service\WdhService;

use App\Models\Bill\BillPay;

use App\Models\Wx\WxCustomer;

use App\Service\Pay\WxPayService;

use App\Models\Promotion\PromotionOrderGift;

use App\Models\Promotion\PromotionOrderGiftGoods;

use App\Models\Promotion\PromotionOrderGiftReceive;

use App\Models\Activity\Lottery\LotteryDraw;

use App\Models\Mall\MallGroup;

use App\Models\Promotion\PromotionOrderGiftCard;

use App\Models\Promotion\PromotionOrderGiftReceiveCard;

class BillController extends Controller
{

    /**
     * 查询订单取消原因
     * @param Request $request
     * @return array
     */
    public function init(Request $request)
    {

        //查询订单取消原因
        $item_data = ConfigureFunction::getConfigure(37);
        return response()->json(['code'=>200,'message'=>'ok','data'=>$item_data]);

    }

    /**
     * 订单列表
     * @param Request $request
     * @return array
     */
    public function search(Request $request)
    {
        $host = $request->getSchemeAndHttpHost();
        $rp = $request->input('rp');
        $type = $request->input('type');//订单状态
        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);

        if ( empty($session_id) ) {
            return response()->json(['code'=>100001,'message'=>'缺少参数：session_id']);
        }

        if ( !ebsig_is_int($rp) ) {
            $rp = 10 ;
        }

        if ( !ebsig_is_int($type) ) {
            $type = 1 ;//默认全部
        }

        //获取客户号
        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 100002, 'message' => '请登录']);
        }

        //查询条件
        $where = [];
        $where[] = ['pcustID',$pcustID];
        switch ($type) {

            case 1 ://全部

                $bill_master = Bill::where($where)
                    ->whereIn('split_type', [1,3])
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;


            case 2: //待付款

                $where[] = ['bill_status','<>',5];
                $where[] = ['pay_type','<>',1];

                $bill_master = Bill::where($where)
                    ->whereIn('pay_status', [0,2])
                    ->whereIn('split_type', [1,3])
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

            case 3: //待发货

                $where[] = ['bill_status',1];

                $bill_master = Bill::where($where)
                    ->whereIn('split_type', [1,3])
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

            case 4: //待收货

                $bill_master = Bill::where($where)
                    ->whereIn('bill_status', [2,3])
                    ->whereIn('split_type', [1,3])
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

            case 5: //已完成

                $where[] = ['bill_status',4];
                $bill_master = Bill::where($where)
                    ->whereIn('split_type', [1,3])
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

            case 6: //退款/货

                $bill_master = Bill::where($where)
                    ->where(function ($query) {
                        $query->where('bill_return_status', '>', 0)
                            ->orWhere('bill_refund_status', '>', 0);
                    })
                    ->whereIn('split_type', [1,3])
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

            case 10: //团购--待成团

                $where[] = ['billType',9];
                $where[] = ['bill_status',0];

                $bill_master = Bill::where($where)
                    ->whereIn('split_type', [1,3])
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

        }

        //返回数组
        $return_data = array(
            'count' => isset($bill_master['total']) ? $bill_master['total'] : 0 ,
            'list' => array()
        );

        //订单取消配置
        $bill_cancel = ConfigureFunction::getConfigureField(21, 'bill_cancel_condition',1);//前端货到付款订单取消条件
        $bill_cancel_onlinepay = ConfigureFunction::getConfigureField(21, 'bill_cancel_condition_onlinepay',1);//前端款到发货订单取消条件

        //退货设置
        $bill_can_return_status = ConfigureFunction::getConfigureField(4, 'bill_return_status',0); // 退货服务状态
        $return_term_of_validity = ConfigureFunction::getConfigureField(4, 'return_term_of_validity',0);//退货退款有效期  单位：天

        $return_time = $return_term_of_validity * 24 * 60 * 60 ;

        if ( !empty($bill_master['data']) ) {

            foreach($bill_master['data'] as &$value) {

                //退款退货标志
                $is_can_return = 0;
                if ($bill_can_return_status) {
                    if (in_array($value['bill_status'], array(2, 3, 6,7,8))) {
                        if ($value['bill_return_status'] != 2 || $value['bill_refund_status'] != 2) {
                            if ($value['pay_status'] == 1 || $value['pay_status'] == 2) {
                                $is_can_return = 1;
                            }
                        }
                    } else if ($value['bill_status'] == 4) {
                        $time = time() - strtotime($value['createTime']);
                        if ($time < $return_time && $value['bill_return_status'] == 0 && $value['bill_refund_status'] == 0) {
                            $is_can_return = 1;
                        }
                    }
                }

                $bill_status_name = '待审核' ;
                if ($value['bill_status'] == 1) {
                    $bill_status_name = '已确认';
                } else if ($value['bill_status'] == 2) {
                    $bill_status_name = '已发货';
                } else if ($value['bill_status'] == 3) {
                    $bill_status_name = '已配送';
                } else if ($value['bill_status'] == 4) {
                    $bill_status_name = '已完成';
                } else if ($value['bill_status'] == 5) {
                    $bill_status_name = '已取消';
                } else if ($value['bill_status'] == 6) {
                    $bill_status_name = '已拒收';
                } else if ($value['bill_status'] == 7) {
                    $bill_status_name = '配货中';
                } else if ($value['bill_status'] == 8) {
                    $bill_status_name = '已配货';
                }

                $bill_return_status_name = '未退货' ;
                if ( $value['bill_return_status'] == 1) {
                    $bill_return_status_name = '部分退货';
                } else if ( $value['bill_return_status'] == 2) {
                    $bill_return_status_name = '已退货';
                }

                $bill_refund_status_name = '未退款';
                if ( $value['bill_refund_status'] == 1) {
                    $bill_refund_status_name = '部分退款';
                } else if ( $value['bill_refund_status'] == 2) {
                    $bill_refund_status_name = '已退款';
                }

                //查询订单商品信息
                $bill_goods = BillGoods::where('bill_no',$value['bill_no'])->get()->toArray();
                $goods_array = array() ;//商品信息
                if ( !empty($bill_goods) ) {
                    foreach($bill_goods as $good) {

                        $good_sale_data = GoodsSaleEdit::select('goodsMainPic')->find($good['goods_postID']);

                        $goods_array[] = array(
                            'goodsName' => $good['goods_name'],
                            'goodsAmount' => $good['goods_amount'],//销售数
                            'img_link' => $host.$good_sale_data['goodsMainPic'],//商品图片
                        );

                    }
                }

                //团购订单
                if ( $value['billType'] == 9 ) {

                    //团购主订单
                    $parent_bill_no = (string)$value['parent_bill_no'];

                    if ( $value['bill_status'] == 1 ) {

                        //团购id
                        $tuan_id = $value['activity_id'];

                        //查询团购信息
                        $tuan_master_data = Tg::find($tuan_id);
                        if ( $tuan_master_data ) {

                            //拼团类型
                            $tuan_type = $tuan_master_data['tuan_type'];
                            //成团人数
                            $success_tuan_num = $tuan_master_data['success_tuan_num'];

                            //团购的购买数量
                            $tuan_buy_num = Redis::get('TG_BUY_NUM_' . $tuan_id);
                            if ( $tuan_buy_num >= 1 ) {

                                $number = $success_tuan_num - $tuan_buy_num;
                                if ( $number > 0 ) {
                                    $left_user_number = $number;
                                } else {
                                    $left_user_number =  0;
                                }

                            }

                        }

                    }

                }

                $is_cancel = 0 ;
                if ( $value['billType'] == 9 ) { //团购订单取消条件
                    if (($value['bill_status'] == 0 && $value['pay_status'] == 0) || ($value['bill_status'] == 1 && $value['pay_status'] == 1)) {
                        $is_cancel = 1;
                    }
                } else { //其他订单取消条件
                    if ( $value['pay_type'] == 1 ) {//货到付款
                        if (($value['bill_status'] == 0 && in_array($bill_cancel, array(1, 2))) || ($value['bill_status'] == 1 && $bill_cancel == 2 && $value['is_enter_erp'] == 0)) {
                            $is_cancel = 1;
                        }
                    } else {//款到发货
                        if (($bill_cancel_onlinepay == 1 && $value['bill_status'] == 0) || ($bill_cancel_onlinepay == 2 && in_array($value['bill_status'], array(0,1)))) {
                            $is_cancel = 1;
                        }
                    }
                }

                $return_data['list'][] = array(
                    'bill_no' => (string)$value['bill_no'], //订单号
                    'ziti' => $value['ziti'], //是否自提 1、是 0，否
                    'bill_total_amount' => $value['bill_total_amount'], //订单商品总数量
                    'pay_status' => $value['pay_status'], //付款状态:0未付款;1全付;2部分付
                    'bill_payable' => $value['bill_payable'], //应付款金额
                    'createTime' => $value['createTime'], //下单时间
                    'billType' => $value['billType'], //订单类型
                    'bill_status' => $value['bill_status'], //订单状态
                    'bill_return_status' => $value['bill_return_status'], // 退货状态    0 ，未退货 1 ，部分退货 2 ，已退货
                    'bill_refund_status' => $value['bill_refund_status'], //退款状态    0 ，未退款 1 ，部分退款 2 ，已退款
                    'is_comment' => $value['is_comment'], //订单商品是否已评论 0：未评论 1：已评论
                    'pay_type' => $value['pay_type'],//支付方式
                    'is_can_return' => $is_can_return,//退货退款标识
                    'parent_bill_no' => isset($parent_bill_no) ? $parent_bill_no : 0,
                    'tuan_type' => isset($tuan_type) ? $tuan_type : '',
                    'left_user_number' => isset($left_user_number) ? $left_user_number : 0 ,
                    'is_cancel' => $is_cancel ,
                    'bill_status_name' => $bill_status_name  ,
                    'bill_return_status_name' => $bill_return_status_name  ,
                    'bill_refund_status_name' => $bill_refund_status_name  ,
                    'goods' => $goods_array, //订单商品信息

                );

            }

        }

        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);

    }

    /**
     * 订单详情
     * @param Request $request
     * @return array
     */
    public function detail (Request $request)
    {

        $host = $request->getSchemeAndHttpHost();
        $bill_no = $request->input('bill_no');
        if ( empty($bill_no) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：bill_no']);
        }

        $fields_array = array('createTime','bill_no','bill_status','bill_return_status','bill_refund_status','bill_totalPaid','bill_subtract_money','bill_points_money',
            'bill_balance_money','bill_coupon_money','bill_payable','bill_total_amount','bill_withdraw_amount','deliver_name','deliver_province','deliver_city','deliver_county',
            'deliver_address','deliver_mobile','sendTypeID','sendTypeName','ziti','deliver_fee','pay_type','pay_status','billType','invoice','invoice_title','invoice_content',
            'parent_bill_no','mallID','mallCode','mallName','activity_id','remark','is_comment','is_enter_erp','pickup_start_time','pickup_end_time','send_time','zt_id','zt_name',
            'zt_code','payTypeName');
        //查询订单信息
        $bill_master = Bill::select($fields_array)
            ->where('bill_no',$bill_no)
            ->first();
        if ( empty($bill_master) ) {
            return response()->json(['code'=>100001,'message'=>'订单信息不存在']);
        }

        //转成数组
        $bill_master = collect($bill_master)->toArray();

        $bill_status = $bill_master['bill_status'];

        $bill_master['bill_no'] = (string)$bill_master['bill_no'];

        $bill_master['bill_status_name'] = '待审核';
        if ($bill_master['bill_status'] == 1) {
            $bill_master['bill_status_name'] = '已确认';
        } else if ($bill_master['bill_status'] == 2) {
            $bill_master['bill_status_name'] = '已发货';
        } else if ($bill_master['bill_status'] == 3) {
            $bill_master['bill_status_name'] = '已配送';
        } else if ($bill_master['bill_status'] == 4) {
            $bill_master['bill_status_name'] = '已完成';
        } else if ($bill_master['bill_status'] == 5) {
            $bill_master['bill_status_name'] = '已取消';
        } else if ($bill_master['bill_status'] == 6) {
            $bill_master['bill_status_name'] = '已拒收';
        } else if ($bill_master['bill_status'] == 7) {
            $bill_master['bill_status_name'] = '配货中';
        } else if ($bill_master['bill_status'] == 8) {
            $bill_master['bill_status_name'] = '已配货';
        }

        $bill_master['bill_return_status_name'] = '未退货';
        if ( $bill_master['bill_return_status'] == 1) {
            $bill_master['bill_return_status_name'] = '部分退货';
        } else if ( $bill_master['bill_return_status'] == 2) {
            $bill_master['bill_return_status_name'] = '已退货';
        }

        $bill_master['bill_refund_status_name'] = '未退款';
        if ( $bill_master['bill_refund_status'] == 1) {
            $bill_master['bill_refund_status_name'] = '部分退款';
        } else if ( $bill_master['bill_refund_status'] == 2) {
            $bill_master['bill_refund_status_name'] = '已退款';
        }

        //订单取消配置
        $bill_cancel = ConfigureFunction::getConfigureField(21, 'bill_cancel_condition',1);//前端货到付款订单取消条件
        $bill_cancel_onlinepay = ConfigureFunction::getConfigureField(21, 'bill_cancel_condition_onlinepay',1);//前端款到发货订单取消条件
        $bill_create_pickup_code = ConfigureFunction::getConfigureField(21, 'bill_create_pickup_code',0);//订单生码规则

        //退货设置
        $bill_can_return_status = ConfigureFunction::getConfigureField(4, 'bill_return_status',0); // 退货服务状态
        $return_term_of_validity = ConfigureFunction::getConfigureField(4, 'return_term_of_validity',0);//退货退款有效期  单位：天

        $return_time = $return_term_of_validity * 24 * 60 * 60 ;

        //退款退货标志
        $is_can_return = 0;
        if ($bill_can_return_status) {
            if (in_array($bill_status, array(2, 3, 6,7,8))) {
                if ($bill_master['bill_return_status'] != 2 || $bill_master['bill_refund_status'] != 2) {
                    if ($bill_master['pay_status'] == 1 || $bill_master['pay_status'] == 2) {
                        $is_can_return = 1;
                    }
                }
            } else if ($bill_status == 4) {
                $time = time() - strtotime($bill_master['createTime']);
                if ($time < $return_time && $bill_master['bill_return_status'] == 0 && $bill_master['bill_refund_status'] == 0) {
                    $is_can_return = 1;
                }
            }
        }

        $bill_master['is_can_return'] = $is_can_return;

        $pickup_time_show = 0;//是否展示时间
        $getGoodsTime = '';//配送或自提时间
        //配送方式一
        if ($bill_master['ziti'] != 1 && !empty($bill_master['send_time'])) {
            $pickup_time_show = 1;
            $getGoodsTime = $bill_master['send_time'];
        } else {
            //自提或配送方式二
            if (!empty($bill_master['pickup_start_time']) && $bill_master['pickup_start_time'] != '0000-00-00 00:00:00') {
                if ( strtotime($bill_master['pickup_end_time']) - strtotime($bill_master['pickup_start_time']) < 86400 ) {
                    $pickup_time_show = 1;
                    $getGoodsTime = date( 'Y-m-d' , strtotime($bill_master['pickup_start_time']) ).' '. date( 'H:i' , strtotime($bill_master['pickup_start_time']) ) .'-' .date( 'H:i' , strtotime($bill_master['pickup_end_time']) );
                }
            }
        }

        //查询订单商品信息
        $bill_goods = BillGoods::where('bill_no',$bill_no)->get()->toArray();

        $goods_array = array() ;//商品信息
        if ( !empty($bill_goods) ) {
            foreach($bill_goods as $k=>$good) {

                $good_sale_data = GoodsSaleEdit::select('goodsMainPic')->find($good['goods_postID']);

                $goods_array[$k] = array(
                    'goodsName' => $good['goods_name'],
                    'goods_purchasePrice' => $good['goods_purchasePrice'],
                    'goodsAmount' => $good['goods_amount'],//销售数
                    'img_link' => $host.$good_sale_data['goodsMainPic'],//商品图片
                    'wap_link' => $host.'/wap/goods-' . $good['goods_postID'] . '.html',//商品链接
                );

            }
        }

        //查询订单轨迹
        $bill_trace = BillTrace::select('createTime','content')->where('bill_no',$bill_no)->orderBy('createTime', 'DESC')->limit(1)->get()->toArray();

        $code_count = 0;
        $barcode = '';

        //查询订单生码信息
        $code_data = BillCodePool::select('barcode')
            ->where('bill_no',$bill_no)
            ->orderBy('createTime','DESC')
            ->get()
            ->toArray();

        if ( $code_data ) {
            if ( $bill_create_pickup_code == 1 ) {//按订单生码
                $barcode = $code_data[0]['barcode'];
            } else if ( $bill_create_pickup_code == 2 ) {//按商品生码
                $code_count = count($code_data);
                if ( $code_count <= 1 ) {
                    $barcode = $code_data[0]['barcode'];
                }

            }

        }

        //如果有门店信息
        $mallInfo = [];
        if ( $bill_master['mallID'] >  0 ) {
            $mallInfo = MallMaster::select('mallName','mallCode','provinceName','cityName','countyName','address','phone','mobile')->where('mallID',$bill_master['mallID'])->first();
            if ( $mallInfo ) {
                $mallInfo = collect($mallInfo)->toArray();
            }

        }

        //自提点信息
        $zttInfo = [];
        if ($bill_master['zt_id'] > 0) {
            $zttInfo = MallZiti::select('zt_code','zt_name','phone','provinceName','cityName','countryName','address','mobile')->where('zt_id',$bill_master['zt_id'])->get()->toArray();
            if ( $zttInfo) {
                $zttInfo = $zttInfo[0];
            }
        }

        /*
        *    待成团的团购订单
        */
        $parent_bill_no = '';//主订单
        $tuan_success_flg = '';//是否成团
        $tuan_type = '';//拼团类型
        $left_user_number = '';//还差多少人

        if ( $bill_master['billType'] == 9 ) {

            //团购主订单
            $parent_bill_no = (string)$bill_master['parent_bill_no'];

            //是否成团
            $tuan_success_flg = 0;
            if ( $bill_status == 1 || $bill_master['pay_status'] == 1 ) {
                $tuan_success_flg = 1;
            }

            if ( $bill_status == 1 ) {

                //团购id
                $tuan_id = $bill_master['activity_id'];

                //查询团购信息
                $tuan_master_data = Tg::find($tuan_id);
                if ( $tuan_master_data ) {

                    //拼团类型
                    $tuan_type = $tuan_master_data['tuan_type'];

                    //成团人数
                    $success_tuan_num = $tuan_master_data['success_tuan_num'];

                    //团购的购买数量
                    $tuan_buy_num = Redis::get('TG_BUY_NUM_' . $tuan_id);
                    if ( $tuan_buy_num >= 1 ) {

                        $number = $success_tuan_num - $tuan_buy_num;
                        if ( $number > 0 ) {
                            $left_user_number = $number;
                        } else {
                            $left_user_number =  0;
                        }

                    }

                }

            }

        }

        $is_cancel = 0;
        if ($bill_master['billType'] == 9) { //团购订单取消条件
            if (($bill_status == 0 && $bill_master['pay_status'] == 0) || ($bill_status == 1 && $bill_master['pay_status'] == 1)) {
                $is_cancel = 1;
            }
        } else {
            if ($bill_master['pay_type'] == 1) {
                if (($bill_status == 0 && in_array($bill_cancel, array(1, 2))) || ($bill_status == 1 && $bill_cancel == 2 && $bill_master['is_enter_erp'] == 0)) {
                    $is_cancel = 1;
                }
            } else {
                if ( ($bill_cancel_onlinepay == 1 && $bill_status == 0) || ($bill_cancel_onlinepay == 2 && in_array($bill_status, array(0,1))) ) {
                    $is_cancel = 1;
                }
            }
        }

        //返回的数据
        $return_data = [
            'pickup_time_show' => $pickup_time_show,
            'getGoodsTime' => $getGoodsTime,
            'master' => $bill_master,//订单信息
            'goods' => $goods_array,//订单商品信息
            'code' => [//券码信息
                'code_count' => $code_count,//券码数量
                'barcode' => $barcode,//券码
            ],
            'mallInfo' => $mallInfo,//门店信息
            'zttInfo' => $zttInfo,
            'tuan' => [    //团购订单信息
                'parent_bill_no' => $parent_bill_no,
                'tuan_success_flg' => $tuan_success_flg,
                'tuan_type' => $tuan_type,
                'left_user_number' => $left_user_number
            ],
            'bill_trace' => $bill_trace[0],//订单轨迹
            'is_cancel' => $is_cancel,//是否可取消订单  0 ，不可 1，可以
        ];

        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);

    }

    /**
     * 查询订单提货券
     * @param Request $request
     * @return array
     */
    public function barcode(Request $request)
    {

        $bill_no = $request->input('bill_no');
        if ( empty($bill_no) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：bill_no']);
        }

        $bill_code_list = [];

        //查询订单生码信息
        $code_data = BillCodePool::select('barcode','bill_no','postID','code_status')
            ->where('bill_no',$bill_no)
            ->orderBy('createTime','DESC')
            ->get()
            ->toArray();

        if ( $code_data ) {

            foreach ( $code_data as &$code ) {

                $bill_goods_data = BillGoods::select('goods_name','goods_purchasePrice')->where([['bill_no' , '=' , $bill_no],['goods_postID', '=' , $code['postID']]])->get()->toArray();
                $code['goods_name'] = $bill_goods_data[0]['goods_name'];
                $code['goods_purchasePrice'] = $bill_goods_data[0]['goods_purchasePrice'];
                $code['goods_amount'] = 1;

            }
            $bill_code_list = $code_data;

        }

        //返回的数据
        $return_data = [
            'list' => $bill_code_list,
        ];

        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);


    }

    /**
     * 订单轨迹
     * @param Request $request
     * @return array
     */
    public function trace(Request $request)
    {

        $bill_no = $request->input('bill_no');
        if ( empty($bill_no) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：bill_no']);
        }

        //查询订单信息
        $bill_master = Bill::select('bill_no','ziti','express_number')
            ->where('bill_no',$bill_no)
            ->first();
        if ( empty($bill_master) ) {
            return response()->json(['code'=>100001,'message'=>'订单信息不存在']);
        }

        //转成数组
        $bill_master = collect($bill_master)->toArray();

        $bill_trace = BillTrace::select('createTime','content')->where('bill_no',$bill_no)->get()->toArray();
        if ( $bill_trace ) {
            foreach ( $bill_trace as &$item ) {
                $item['time']= explode(' ',$item['createTime']);
            }

        }

        $return_data = array(
            'bill_no' => (string)$bill_master['bill_no'],
            'express_number' => (string)$bill_master['express_number'],//快递单号
            'ziti' => $bill_master['ziti'],
            'trace' => $bill_trace
        );

        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);

    }

    /**
     * 取消订单
     * @param Request $request
     * @return \array
     * @throws \Exception
     */
    public function cancel( Request $request )
    {

        $bill_no = $request->input('bill_no');
        $session_id = $request->input('session_id', session_id());
        $platform = $request->input('platform', 6);
        $cancel_reason = $request->input('cancel_reason');
        $bill_status = $request->input('bill_status');

        if ( empty($bill_no) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：bill_no']);
        }

        if (empty($session_id)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：session_id']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 100002, 'message' => '请登录']);
        }

        $customer = Customer::select('custID')->find($pcustID);

        $request_data = array(
            'bill_no' => $bill_no,
            'custID' => $customer->custID,
            'bill_status' => $bill_status,
            'cancel_reason' => $cancel_reason
        );

        $return_data = WdhService::cancel($request_data);

        return response()->json(['code'=>$return_data['code'],'message'=>$return_data['message']]);

    }

    /**
     * 检查订单和支付
     */
    public function checkBillPay ( Request $request ) {

        $bill_no = $request->input('bill_no',0);
        $session_id = $request->input('session_id', session_id());
        $payTypeID = $request->input('payTypeID', 0 );
        $platform = $request->input('platform', 6);

        if ( empty( $bill_no ) ) {
            return response()->json(['code' => 10000, 'message' => '参数参数：bill_no']);
        }

        $pcustID = get_customer_id($session_id, $platform);
        if (!$pcustID) {
            return response()->json(['code' => 10001, 'message' => '请先登录']);
        }

        //查询主订单
        $bill_data = Bill::getBill( $bill_no );
        if ( !$bill_data ) {
            return response()->json(['code' => 10002, 'message' => '订单不存在']);
        }

        //订单状态
        if ( $bill_data->bill_status == 1 ) {
            return response()->json(['code' => 10003, 'message' => '订单已确认']);
        } else if ( $bill_data->bill_status == 2 ) {
            return response()->json(['code' => 10004, 'message' => '订单已发货']);
        } else if ( $bill_data->bill_status == 3 ) {
            return response()->json(['code' => 10005, 'message' => '订单已配送']);
        } else if ( $bill_data->bill_status == 4 ) {
            return response()->json(['code' => 10006, 'message' => '订单已完成']);
        } else if ( $bill_data->bill_status == 5 ) {
            return response()->json(['code' => 10007, 'message' => '订单已取消']);
        } else if ( $bill_data->bill_status == 6 ) {
            return response()->json(['code' => 10008, 'message' => '订单异常']);
        } else if ( $bill_data->bill_status == 7 ) {
            return response()->json(['code' => 10009, 'message' => '订单配货中']);
        } else if ( $bill_data->bill_status == 8 ) {
            return response()->json(['code' => 10010, 'message' => '订单配货完成']);
        }

        if ( !ebsig_is_int( $payTypeID ) ) {
            $payTypeID = $bill_data->payTypeID;
        }

        //返回的数据
        $return_array = array(
            'payTypeID' => $payTypeID,
            'pay_status' => $bill_data->pay_status,
            'pay_type' => $bill_data->pay_type,
            'online_pay' => array(),
            'bill_payable' => $bill_data->bill_payable,
            'pay_data' => array(
                'code' => 200
            ),
            'success_pay_jump_url' => '',
            //付款结束时间
            'pay_end_time' => ''
        );

        //如果是在线支付
        if ( $bill_data->pay_type == 2 && in_array( $bill_data->pay_status, array(0, 2) ) ) {

            $bill_pay_time = ConfigureFunction::getConfigureField(21,'bill_pay_time');
            if ( $bill_pay_time ) {
                $return_array['pay_end_time'] = strtotime ("+" . $bill_pay_time . " hour", strtotime($bill_data->createTime)) * 1000;
            }

            //在线支付参数数组
            $return_array['online_pay'][] = array(
                'payTypeID' => 50,
                'payTypeName' => 'wei',
                'alias' => 'weixin',
                'payment_platform' => 2,
                'memo' => '微信支付',
                'logo_img' => $request->getSchemeAndHttpHost().'/static/images/m/checkout/weixin-pay.png',
                'selected' => 1
            );

            if ( $bill_data->pay_status != 1 ) {

                $pay_amount = 0;

                //订单支付方式
                $pay_data = BillPay::getPay( $bill_data->bill_no );
                foreach( $pay_data as $pay ) {
                    if ( $pay['type'] == 2) {
                        $pay_amount = $pay['pay_amount'];
                    }
                }

                $openId = '';
                $trade_type = '';

                $wx_config_seeting = ConfigureFunction::getConfigureField(41,'wechat_type');

                if ( $wx_config_seeting == 1) {

                    $trade_type = 'JSAPI';

                    $customer_data = app('redis')->get('WX_APPLET_USER_' . $session_id);
                    $customer_data = json_decode($customer_data, true);
                    $openId = $customer_data['openId'];

                }

                if ( $wx_config_seeting != 1 ) {
                    $trade_type = 'NATIVE';
                }

                //微信异步接收路径
                $notify_url = $request->getSchemeAndHttpHost() . '/onlinepay/weixin/notify';

                $params = [
                    'out_trade_no' => $bill_data->bill_no,
                    'trade_type' => $trade_type,
                    'payTypeID' => 50,
                    'mallID' => $bill_data->mallID,
                    'body' => '微商城',
                    'total_fee' => $pay_amount,
                    'pcustID' => $pcustID,
                    'type' => 4,
                    'openId' => $openId,
                    'notify_url' => $notify_url
                ];

                $WxPayService = new WxPayService($params);

                $wx_pay = $WxPayService->request();
                if ($wx_pay['code'] == 200) {
                    $return_array['pay'] = $wx_pay['data'];
                }

            } else {
                $return_array['pay'] = [];
            }

        }

        if (  !empty( $bill_data->activity_id ) ) {
            if ( $bill_data->billType == 2) {
                $return_array['success_pay_jump_url'] = '/wap/special/card/' . $bill_data->activity_id . '.html';
            } elseif ( $bill_data->billType == 3) {
                $return_array['success_pay_jump_url'] = '/wap/flash/card/' . $bill_data->activity_id . '.html';
            } elseif ($bill_data->billType == 7) {
                $return_array['success_pay_jump_url'] = '/wap/ticket.html?activity_id=' . $bill_data->activity_id . '&activity_type=17';
            }
        }

        if ( $bill_data->pay_type == 1 ) {
            $billPromotionData = redisTransformation(Redis::get('billPromotion_'.$bill_no.$pcustID));
            $return_array['billPromotionLink'] = $billPromotionData['billPromotionLink'];
            $return_array['billPromotionName'] = $billPromotionData['billPromotionName'];
        }

        if ($return_array['bill_payable'] < 0) {
            $return_array['bill_payable'] = 0;
        }

        return response()->json(['code' => 200, 'message' => 'ok' , 'data' => $return_array]);

    }

    /**
     * 支付结果接口
     * @param Request $request
     * @return mixed
     */
    public function payResult(Request $request)
    {

        $bill_no = $request->input('order_no','');
        $mall_id = $request->input('mall_id',0);
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id',session_id() );
        if (empty($session_id)) {
            return response()->json(['code' => 10000, 'message' => '缺少参数：session_id']);
        }

        if ( empty( $bill_no ) ) {
            return response()->json(['code' => 10000 , 'message' => '缺少订单号' ]);
        }

        //查询会员信息
        $pcust_id = get_customer_id( $session_id , $platform );
        if ( !$pcust_id ) {
            return response()->json(['code' => 10003, 'message' => '会员未登录']);
        }

        //选择门店
        $is_open_choose_mall = ConfigureFunction::getConfigureField(8,'is_open_choose_mall');
        if ( $is_open_choose_mall ) {
            if ( empty( $mall_id ) || !ebsig_is_int( $mall_id ) ) {
                $mall_id = redisTransformation( Redis::get($session_id.'G_CHOOSE_MALL_ID'));
            }
        }

        //查询订单信息
        $bill_data = Bill::where( 'bill_no' , $bill_no )->first();
        if ( empty( $bill_data ) || $bill_data->pcustID != $pcust_id ) {
            return response()->json(['code' => 10001 , 'message' => '订单不存在' ]);
        }

        /*
         * 订单满足的促销活动
         */
        $res_promotion = [];

        //查询活动
        $time = Carbon::now();
        $where = [
            [ 'start_time' , '<=' ,$time ],
            [ 'end_time' , '>=' ,$time ],
            [ 'useFlg' , '=' ,1 ]
        ];
        $promotion_data = PromotionOrderGift::where($where)->orderBy('priority','desc')->get()->toArray();

        if ( !empty( $promotion_data ) ) {

            foreach ( $promotion_data as $promotion ) {

                //平台json 1、wap 2、PC 3、app 4、微信小程序
                if ( $promotion['platform'] ) {
                    $promotion_platform = json_decode( $promotion['platform'] , true );
                    if ( $platform == 0 || $platform == '0' ) {
                        $platform = 1;
                    }
                    if ( !in_array( $platform , $promotion_platform ) ) {
                        continue;
                    }
                }

                //是否首单生效
                if ( $promotion['first_order'] ) {
                    $bill_num = Bill::where('pcustID',$pcust_id)->count();
                    if ( $bill_num > 1 ) {
                        continue;
                    }
                }

                //是否可使用卡券 1、是 0、否
                if ( $promotion['use_card_coupon'] == 0 ) {
                    if ( $bill_data->bill_coupon_money > 0 || $bill_data->bill_card_money > 0 ) {
                        continue;
                    }
                }

                //会员等级json，[1,2,3]
                if ( $promotion['rank'] ) {

                    //查询会员等级
                    $cust_data = Customer::where('pcustID',$pcust_id)->first();
                    if ( !$cust_data ) {
                        continue;
                    }
                    $rank = json_decode( $promotion['rank'] , true );
                    if ( !in_array( $cust_data->rankID , $rank ) ) {
                        continue;
                    }

                }

                //门店规则 1、全部门店 2、部分门
                if ( $promotion['store_rule'] == 2 ) {

                    if ( !$promotion['store_group_id'] ) {
                        continue;
                    }

                    $is_exist_mall = false;

                    //门店组id
                    $store_group_id = json_decode($promotion['store_group_id'],true);
                    foreach ( $store_group_id as $item ) {
                        $mall_group = MallGroup::getCache( $item );
                        if ( $mall_group && isset( $mall_group['map'][$mall_id] ) ) {
                            $is_exist_mall = true;
                            break;
                        }
                    }

                    if ( !$is_exist_mall ) {
                        continue;
                    }

                }

                //统计订单满足促销活动的商品件数和金额
                $amount = 0;
                $total_money = 0;

                //订单商品
                $bill_goods = BillGoods::where('bill_no',$bill_no)->get()->toArray();
                if ( !$bill_goods ) {
                    continue;
                }

                //商品规则 1、全部商品 2、部分商品
                if ( $promotion['goods_rule'] == 1 ) {

                    foreach ( $bill_goods as $item ) {
                        $amount += $item['goods_amount'];
                        $total_money += round( $item['goods_purchasePrice']*$item['goods_amount'] , 2 );
                    }

                } else if ( $promotion['goods_rule'] == 2 ) {

                    //促销活动商品
                    $promotion_goods = PromotionOrderGiftGoods::getCache( $promotion['id'] );
                    if ( !$promotion_goods ) {
                        continue;
                    }

                    foreach ( $bill_goods as $item ) {

                        //商品关系 1、包含 2、排斥
                        if ( $promotion['goods_relation'] == 1 ) {
                            if ( in_array( $item['goods_postID'] , $promotion_goods ) ) {
                                $amount += $item['goods_amount'];
                                $total_money += round( $item['goods_purchasePrice']*$item['goods_amount'] , 2 );
                            }
                        } else if ( $promotion['goods_relation'] == 2 ) {
                            if ( !in_array( $item['goods_postID'] , $promotion_goods ) ) {
                                $amount += $item['goods_amount'];
                                $total_money += round( $item['goods_purchasePrice']*$item['goods_amount'] , 2 );
                            }
                        }

                    }

                }

                //赠送倍数
                $gift_card_multiple = 1;

                // 条件类型 1、满X元 2、满X件
                if ( $promotion['condition_type'] == 1 ) {
                    if ( $total_money < $promotion['condition_content'] ) {
                        continue;
                    } else {
                        if ( $promotion['sub_type'] == 6 ) {
                            $gift_card_multiple = floor($total_money/$promotion['condition_content']);
                        }
                    }
                } else if ( $promotion['condition_type'] == 2 ) {
                    if ( $amount < $promotion['condition_content'] ) {
                        continue;
                    } else {
                        if ( $promotion['sub_type'] == 6 ) {
                            $gift_card_multiple = floor($amount/$promotion['condition_content']);
                        }
                    }
                } else {
                    continue;
                }

                //查询活动记录
                $gift_receive = PromotionOrderGiftReceive::where(['promotion_id'=>$promotion['id'],'pcustID'=>$pcust_id,'bill_no'=>$bill_no])->first();
                if ( !$gift_receive ) {

                    //保存活动记录
                    $id = PromotionOrderGiftReceive::insertGetId([
                        'uuid' => makeUuid(),
                        'timeStamp' => Carbon::now(),
                        'creator' => 'system',
                        'createTime' => Carbon::now(),
                        'promotion_id' => $promotion['id'],
                        'promotion_type' => $promotion['sub_type'],
                        'pcustID' => $pcust_id,
                        'bill_no' => $bill_no,
                        'receive_status' => 1,
                        'activity_id' => $promotion['activity_id'],
                        'increase_times' => 0,
                        'gift_card_multiple' => $gift_card_multiple,
                        'is_share' => 0
                    ]);

                    //保存分享卡券
                    if ( $promotion['sub_type'] == 6 || $promotion['sub_type'] == 7 || $promotion['sub_type'] == 8 ) {

                        //查询促销卡券
                        $gift_card = PromotionOrderGiftCard::getCache($promotion['id']);
                        if ( empty( $gift_card ) ) {
                            continue;
                        }
                        $receive_card = [];

                        foreach ( $gift_card as $card ) {

                            //优惠券倍数
                            if ( $promotion['sub_type'] == 6 ) {
                                $card['card_num'] = $card['card_num']*$gift_card_multiple;
                            }

                            for( $i = 0 ; $i < $card['card_num'] ; $i++ ) {

                                $tips_win = '';
                                if ( $promotion['sub_type'] == 7 ) {
                                    $tips_win = array_rand([
                                        '手速3秒' => '1',
                                        '此包只应天上有' => '2',
                                        '换个姿势领' => '3',
                                        '手气更佳' => '4',
                                        '手快有，手慢无' => '5',
                                    ]);
                                }

                                $receive_card[] = [
                                    'uuid' => makeUuid(),
                                    'timeStamp' => Carbon::now(),
                                    'creator' => 'system',
                                    'createTime' =>  Carbon::now(),
                                    'receive_id' => $id,
                                    'promotion_id' => $promotion['id'],
                                    'type' => $promotion['sub_type'],
                                    'pcustID' => $pcust_id,
                                    'card_id' => $card['card_id'],
                                    'user_id' => 0,
                                    'most' => $card['most'],
                                    'remark' =>'',
                                    'tips_win' => $tips_win
                                ];
                            }
                        }

                        //打乱数组
                        shuffle( $receive_card );

                        //保存分享卡券
                        PromotionOrderGiftReceiveCard::insert( $receive_card );

                        //以活动优先级作为key
                        $res_promotion[] = ['type' => $promotion['sub_type'] , 'id' => $id , 'num' => count($receive_card) ];
                        break;
                    } else {
                        //以活动优先级作为key
                        $res_promotion[] = ['type' => $promotion['sub_type'] , 'id' => $id ];
                        break;
                    }

                } else {

                    if ( $promotion['sub_type'] == 6 || $promotion['sub_type'] == 7 || $promotion['sub_type'] == 8 ) {
                        $where = ['receive_id'=> $gift_receive->id,'promotion_id'=>$promotion['id'],'type'=>$promotion['sub_type'],'pcustID'=>$pcust_id];
                        $count = PromotionOrderGiftReceiveCard::where($where)->count();
                        $res_promotion[] = ['type' => $promotion['sub_type'] , 'id' => $gift_receive->id , 'num' => $count ];
                        break;
                    } else {
                        $res_promotion[] = ['type' => $promotion['sub_type'] , 'id' => $gift_receive->id ];
                        break;
                    }

                }


            }

        }

        $data = [
            'payable' => app_to_float($bill_data->bill_payable),
            'status' => app_to_int($bill_data->pay_status),
            'promotion' => $res_promotion
        ];

        return response()->json(['code' => 200, 'message' => 'ok' , 'data' => $data ]);

    }

}
